#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <string.h>
#include "cgic.h"
#include "session.h"

char *success_json="{\"STATUS\":\"SUCCESS\"}";
char *success_json2="{\"STATUS\":\"SUCCESS\",\"name\":\"%s\",\"avatar\":\"%s\"}";
char *faild_json="{\"STATUS\":\"FAIL\",\"ERROR\":\"%s\"}";

int cgiMain() {
	
	char token[100];  
	char out[1024];
	
	int ret = cgiCookieString("token", token,17);//获取用户的token
	
	//这里为了能够跨域还要能带COOKIE 做点操作
	fprintf(cgiOut,"Access-Control-Allow-Credentials: true\r\n");
	if(cgiOrigin){
		sprintf(out,"Access-Control-Allow-Origin: %s\r\n",cgiOrigin);
		fprintf(cgiOut,out); 
	}else{
		fprintf(cgiOut,"Access-Control-Allow-Origin: *\r\n");
	}
	
	
	if(ret!=cgiFormSuccess){
		//token有问题小老弟 没有从cookie中获取到token
		//试试其他方法获取
		ret = cgiFormString("token", token, 17);
		if(ret!=cgiFormSuccess){
			// 两种方法都没获取到
			cgiHeaderContentType("text/html");
			sprintf(out,faild_json,"TOKEN GET ERROR");
			fprintf(cgiOut,out);
			return 0;
		}
		
	}
	if(has_session(token)){
		//确实有该token
		char str[256];
		char username[256];
		char avater[256];
		char *find;
		strcpy(str,"./sess_");
		strcat(str,token);
		FILE *fp = fopen(str,"r");
		fgets(str,12,fp);   //空读时间字段
		fgets(username,100,fp);  //读取用户名称
		find = strchr(username, '\n');          //查找换行符
		if(find)                            //如果find不为空指针
			*find = '\0';                    //就把一个空字符放在这里
		
		fgets(avater,100,fp); 
		find = strchr(avater, '\n');          //查找换行符
		if(find)                            //如果find不为空指针
			*find = '\0';                    //就把一个空字符放在这里
		
		cgiHeaderContentType("text/html");
		sprintf(out,success_json2,username,avater);
		fprintf(cgiOut,out);
		fclose(fp);
	}else{
		cgiHeaderContentType("text/html");
		sprintf(out,faild_json,"TOKEN INVALID");
		fprintf(cgiOut,out);
	}
	

	
	
	return 0;
	
}
